package com.rmuti.datastructure.list;

public class SinglyLinkedList {

	private class LinkedNode {
		private Object element;
		private LinkedNode next;

		LinkedNode(Object e, LinkedNode p) {
			element = e;
			next = p;
		}

	}

	private LinkedNode header;
	private int size;

	public SinglyLinkedList() {
		header = new LinkedNode(null, null);
		size = 0;
	}

	public void add(int i, Object e) {
		LinkedNode p = nodeAt(i - 1);
		p.next = new LinkedNode(e, p.next);
		size++;
	}

	public void add(Object e) {
		add(size, e);
	}

	public Object get(int i) {
		return nodeAt(i).element;
	}

	public void set(int i, Object e) {
		LinkedNode node = nodeAt(i);
		node.element = e;
	}

	public void remove(Object e) {
		LinkedNode p = header;
		while (p != null && !p.next.element.equals(e)) {
			p = p.next;
		}
		if (p.next != null)
			p.next = p.next.next;
	}

	public boolean contains(Object e) {
		LinkedNode node = header.next;
		while (node != null && !node.element.equals(e)) {
			node = node.next;
		}
		return node != null;
	}

	@Override
	public String toString() {
		String ret = "[";
		LinkedNode node = header.next;
		while (node != null) {
			ret += node.element.toString() + ", ";
			node = node.next;
		}
		if (ret.length() > 1) {
			ret = ret.substring(0, ret.length() - 2);
		}
		return ret + "]";
	}

	private LinkedNode nodeOf(Object e) {
		LinkedNode node = header.next;
		while (!node.element.equals(e)) {
			node = node.next;
		}
		return node;
	}

	private LinkedNode nodeAt(int n) {
		LinkedNode p = header;
		for (int i = -1; i < n; i++) {
			p = p.next;
		}
		return p;
	}

	public static void main(String[] args) {
		SinglyLinkedList lst = new SinglyLinkedList();
		lst.add("1");
		lst.add("2");
		lst.add("3");
		lst.remove("2");
		System.out.println(lst);
	}

}
